package com.atguigu.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.auth.fengin.MemberFeignService;
import com.atguigu.auth.service.SmsService;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.auth.vo.UserLoginVo;
import com.atguigu.auth.vo.UserRegisterVo;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ShiJieLin
 * @Date 2022/4/20 22:29
 * @Version 1.0
 */
@Controller
@Slf4j
public class LoginController {

    @Resource
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        // 1.先从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_REG + phone);
        // 2.如果能取到，就判断是否超时
        if (!StringUtils.isEmpty(redisCode)) {
            // 活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                // 60s内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 3.调用第三方服务，发送短信验证码
        Boolean isSend = smsService.send(phone);

        if (!isSend) {
            return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 用户注册
     * TODO: 重定向携带数据：利用session原理，将数据放在session中。
     * TODO:只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO：分布下session问题
     * @param vos
     * @param result
     * @param attributes RedirectAttributes：重定向也可以保留数据，不会丢失
     * @return
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes attributes) {
        // 1.如果JSR303数据校验有错误
        if (result.hasErrors()) {
            // 1.2将检验的异常封装
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage));

            attributes.addFlashAttribute("errors", errors);
            // 效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 2.校验验证码是否正确
        String phone = vos.getPhone();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_REG + phone);
        // 2.1如果验证码不为空
        if (!StringUtils.isEmpty(redisCode)) {
            // 分割验证码
            String[] split = redisCode.split("_");
            redisCode = split[0];
            // 验证码不通过
            if (!redisCode.equals(vos.getCode())) {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            // 如果验证码通过，先删除redis中的验证码
            redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_REG + phone);
            // 调用远程服务，保存用户数据
            R register = memberFeignService.register(vos);
            // 判断是否注册成功
            if (register.getCode() == 0) {

                // 注册成功
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                // 失败
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", register.getData("msg", new TypeReference<String>() {
                }));
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes,
                        HttpSession session) {
        // 1.调用远程方法进行，登陆
        R login = memberFeignService.login(vo);
        // 2.验证成功
        if(login.getCode() == 0){

            MemberResponseVo loginUser = login.getData(new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, loginUser);
            log.info("登陆成功: {}", loginUser);
            return "redirect:http://gulimall.com";
        }else { // 验证失败，跳转登陆页面
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg", new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /** 千万登陆页面，得先判断是否登陆，
     * @param session
     * @return
     */
    @GetMapping("/login.html")
    public String loginToPage(HttpSession session){

        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);

        if(null != loginUser){
            return "redirect:http://gulimall.com";
        }
        return "login";
    }


}
